package com.ruoyi.project.zxcrm.quartz.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.manager.AsyncManager;
//import com.ruoyi.project.zxcrm.domain.CrmLead;
import com.ruoyi.project.zxcrm.domain.CrmSmsLog;
import com.ruoyi.project.zxcrm.domain.CrmSmsTemplate;
import com.ruoyi.project.zxcrm.enums.SmsSDKEnum;
import com.ruoyi.project.zxcrm.mapper.*;
import com.ruoyi.project.zxcrm.quartz.factory.AsyncErrFactory;
import com.ruoyi.project.zxcrm.service.ICrmSmsTemplateService;
import com.ruoyi.project.zxcrm.thirdParty.PullSmsSendStatus;
import com.ruoyi.project.zxcrm.utils.verifyPhone;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Qbzzz
 * @version 1.0
 * @description: 短信自动发送
 * @date 2023/2/16 17:20
 */

@Log4j2(topic = "SmsTask")
@Component("smsTask")
@RequiredArgsConstructor
public class SmsTask {
    private final ICrmSmsTemplateService crmSmsTemplateService;

    private final CrmSmsTemplateMapper crmSmsTemplateMapper;

    private final CrmSmsSendLogMapper crmSmsSendLogMapper;

    private final RedisTemplate<Object, Object> redisTemplate;

    private final CrmLeadMapper crmLeadMapper;

    private final CrmOrderMapper crmOrderMapper;

    private final SmsChannelMapper smsChannelMapper;

    public void LogRecord() {
        String uuid = UUID.randomUUID().toString();
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent("lockA", uuid, 20, TimeUnit.SECONDS);
        if (isLock) {
            try {
                List<PageData> crmLeads = crmLeadMapper.queryAll();
                List<CrmSmsTemplate> crmSmsTemplates = crmSmsTemplateService.selectCrmSmsTemplateList();
                crmLeads.stream().forEach(a -> {
                    if (!verifyPhone.verifyPhone(a.getString("mobile"))) {
                        return;
                    }
                    int numCount = crmSmsSendLogMapper.queryPhoneNum(a.getString("mobile"));
                    int typeCount = crmSmsTemplateMapper.queryTypeCount(a.getString("type"));
                    if (numCount != typeCount) {
                        crmSmsTemplates
                                .stream()
                                .filter(b -> !a.get("type").equals("10")
                                        && a.get("type").equals(b.getType()))
                                .forEach(c -> {
                                    CrmSmsLog crmSmsLog = new CrmSmsLog(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, a.get("create_time").toString().replace("T", " ")));
                                    crmSmsLog.setStatus(0);
                                    crmSmsLog.setSmsLogName(a.getString("partner_name"));
                                    crmSmsLog.setCustomerPhone(a.getString("mobile"));
                                    crmSmsLog.setSmsDay(c.getTDay());
                                    crmSmsLog.setTId(Integer.parseInt(c.getId() + ""));
                                    crmSmsSendLogMapper.insertSmsLog(crmSmsLog);
                                });
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>(script, Long.class);
                redisTemplate.execute(defaultRedisScript, Arrays.asList("lockA"), uuid);
            }
        }
    }

    /**
     * 短信发送
     */
    public void smsSend() {
        String uuid = UUID.randomUUID().toString();
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 20, TimeUnit.SECONDS);
        if (isLock) {
            //用户
            try {
                List<CrmSmsLog> crmSmsLogs = crmSmsSendLogMapper.querySmsLogList();
                crmSmsLogs.stream().forEach(a -> {
                    extracted(a);
                });
            } catch (Exception e) {
                throw new RuntimeException();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>(script, Long.class);
                redisTemplate.execute(defaultRedisScript, Arrays.asList("lock"), uuid);
            }
        }
    }

    /**
     * 检查发送日志表是否有已经有订单提交的用户
     */
    public void checkSmsLogStatus() {
        List<PageData> crmLeads = crmOrderMapper.queryCrmLeadList();
        crmLeads.stream().forEach(a -> {
            List<CrmSmsLog> crmSmsLogs = crmSmsSendLogMapper.queryPhoneNumCustomer(a.getString("mobile"));
            if (crmSmsLogs.size() > 0) {
                crmSmsSendLogMapper.updateStatus(crmSmsLogs);
            }
        });
    }

    //TODO 目前是单手机号发送,后续可以更多手机号发送
    private void extracted(CrmSmsLog a) {
        try {
            CrmSmsTemplate crmSmsTemplate = crmSmsTemplateMapper.queryCrmSmsTemplateId(Long.valueOf(a.getTId()));
            //查询对应的ApiKV
            PageData pd = smsChannelMapper.selectSmsChannelById(crmSmsTemplate.getSms_source());
            //发送信息
            a.setStatus(1);
            AtomicReference<Boolean> result = new AtomicReference<>(false);
            if (SmsSDKEnum.TENG_XUN.getType() == crmSmsTemplate.getSms_source()) {
                result.set(PullSmsSendStatus.TXSmsSend(new String[]{a.getCustomerPhone()}, Long.valueOf(crmSmsTemplate.getTemplateText()),pd));
            } else if (SmsSDKEnum.JING_KAI.getType() == (crmSmsTemplate.getSms_source())) {
                result.set(PullSmsSendStatus.JKSmsSend(a.getCustomerPhone(), crmSmsTemplate.getTemplateText(), pd));
            }
            if (!result.get()) {
                a.setStatus(2);
            }
            crmSmsSendLogMapper.updateSmsLog(a);
        } catch (RuntimeException  | TencentCloudSDKException e) {
            a.setStatus(2);
            AsyncManager.me().execute(AsyncErrFactory.recordErrLog(e.getMessage(), a));
            log.error("异常信息是===>{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @SneakyThrows
    public static void main(String[] args) {
        Date parse = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS).parse("2023-06-13 14:46:34");
        System.out.println(parse);
    }
}
